package demo;

import java.util.Deque;
import java.util.LinkedList;

class MyStack {

    private Deque<Integer> deque1;
    private Deque<Integer> deque2;
    public MyStack() {
        deque1 = new LinkedList<>();
        deque2 = new LinkedList<>();
    }
    
    public void push(int x) {
        if(!deque1.isEmpty()){
            deque1.offer(x);
        } else if(!deque2.isEmpty()){
            deque2.offer(x);
        } else {
            deque1.offer(x);
        }
    }
    
    public int pop() {
        if(deque2.isEmpty()){
            int sz = deque1.size();
            for(int i = 0; i < sz - 1; i++){
                deque2.offer(deque1.poll());
            }
            return deque1.poll();
        } else{
            int sz = deque2.size();
            for(int i = 0; i < sz - 1; i++){
                deque1.offer(deque2.poll());
            }
            return deque2.poll();
        }
    }
    
    public int top() {
        if(deque2.isEmpty()){
            int sz = deque1.size();
            int val = -1;
            for(int i = 0; i < sz; i++){
                val = deque1.poll();
                deque2.offer(val);
            }
            return val;
        } else{
            int sz = deque2.size();
            int val = -1;
            for(int i = 0; i < sz; i++){
                val = deque2.poll();
                deque1.offer(val);
            }
            return val;
        }
    }
    
    public boolean empty() {
        return deque1.isEmpty() && deque2.isEmpty();
    }
}